package org.example.sringbootdemo.dao;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import org.example.sringbootdemo.entity.Fruit;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@Component
public class FruitDao {
    public List<Fruit> getAll() {
        try {
            List<Entity> tableGoods = Db.use().query("select * from table_goods");
            List<Fruit> fruits = new ArrayList<>();

            for (Entity entity : tableGoods) {
                Fruit fruit = new Fruit();
                fruit.setName(entity.getStr("name"));
                fruit.setPrice(entity.getBigDecimal("price"));
                fruit.setCode(entity.getStr("code"));
                fruits.add(fruit);
            }

            return fruits;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public String add(Fruit nfruit) {
        try {
            Db.use().insert(
                    Entity.create("table_goods")
                            .set("name", nfruit.getName())
                            .set("price", nfruit.getPrice())
                            .set("code", nfruit.getCode())
            );

            return "Done";
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public String delete(String code) {
        try {
            Db.use().del("table_goods", "code", code);

            return "Done";
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        FruitDao dao = new FruitDao();
    }
}
